package com.zx.idc.backend.gui.config.aspect;

import com.zx.idc.backend.gui.common.util.AjaxUtil;
import com.zx.idc.backend.gui.common.util.NetworkUtil;
import com.zx.idc.common.exception.GlobalException;
import com.zx.idc.common.util.ProcessUtil;
import com.zx.idc.ds.tlog.entity.TLogSystem;
import com.zx.idc.ds.tlog.service.ITLogSystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;

/**
 * 记录系统日志
 *
 * @author rxliuli
 */
@Component
public class SystemLogInterceptor implements HandlerInterceptor {
    @Autowired
    private ITLogSystemService tlogSystemService;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (!AjaxUtil.isAjax(request)) {
            return;
        }
        final LocalDateTime now = LocalDateTime.now();
        final String pid = ProcessUtil.getPid();
        final String ip = NetworkUtil.getIpAddress(request);
        final String location = request.getRequestURI();
        final TLogSystem tlogSystem = new TLogSystem(now, location, pid, ip);
        if (ex == null) {
            tlogSystem.setLevel(TLogSystem.LEVEL_INFO);
        } else {
            if (ex instanceof GlobalException) {
                tlogSystem.setLevel(TLogSystem.LEVEL_WARNING);
            } else {
                tlogSystem.setLevel(TLogSystem.LEVEL_DANGER);
            }
            tlogSystem.setMessage(ex.getMessage());
        }
        CompletableFuture.runAsync(() -> tlogSystemService.insert(tlogSystem));
    }
}
